import csv
import os
from pathlib import Path

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap

from PyQt5.QtWidgets import *



# 继承基类和自己写的UI类
from const import USER_CONFIG
from main_ui import Ui_MainWindow
from tools import clear_layout, getTimeStamp, modify_row, adjust_columns_width, readJson, saveJson
dir_path = os.path.dirname(os.path.abspath(__file__))
USER_CONFIG_FILE = os.path.join(dir_path,'config.json')
print(USER_CONFIG_FILE)
class MainWindow(QMainWindow, Ui_MainWindow):
    csvData = []
    csvPath = ''
    def __init__(self):

        super(MainWindow, self).__init__()
        self.setupUi(self)
        # data = {
        #     "姓名": "张三",
        #     "年龄": "25",
        #     "性别": "男",
        #     "职业": "工程师",
        #     "电话": "13800138000",
        #     "邮箱": "zhangsan@example.com",
        #     "地址": "北京市海淀区",
        #     "部门": "研发部",
        #     "工号": "A1001",
        #     "入职日期": "2020-01-01",
        #     "薪资": "20000",
        #     "学历": "本科",
        #     "状态1": "在职",
        #     "备注2": "无",
        #     "技能3": "Python, C++",
        #     "状态4": "在职",
        #     "备注5": "无",
        #     "技能6": "Python, C++",
        #     "状态7": "在职",
        #     "备注": "无",
        #     "技能": "Python, C++",
        #     "项目": "OA系统开发"
        # }
        #
        # # 创建网格布局（6行x3列）
        # grid = QGridLayout()
        # # grid.setSpacing(10)  # 设置间距
        # self.csvWidget.setLayout(grid)
        # row, col = 0, 0
        # for key, value in data.items():
        #     # 第一列：属性名 + 冒号
        #     lbl_key = QLabel(f"{key}:")
        #     lbl_key.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        #
        #     # 第三列：属性值
        #     lbl_value = QLabel(value)
        #     lbl_value.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        #
        #     # 添加到网格
        #     grid.addWidget(lbl_key, row, col)
        #     grid.addWidget(lbl_value, row, col +2)
        #
        #     # 更新行和列
        #     col += 3
        #     if col >= 9:  # 每行3组（3列x3=9，因为每组占3列）
        #         col = 0
        #         row += 1
        self.initConnect()

    def initConnect(self):
        self.loadCsvBtn.clicked.connect(self.open_csv)
        self.csvTable.itemSelectionChanged.connect(self.showCsvTableRow)
        self.upBtn.clicked.connect(self.upFunc)
        self.downBtn.clicked.connect(self.downFunc)
        self.saveBtn.clicked.connect(self.saveCsv)
        self.isRetainCheck.clicked.connect(self.isRetain)
    def open_csv(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择 CSV 文件",
            "",
            "CSV 文件 (*.csv);;所有文件 (*)"
        )

        if not file_path:  # 用户取消选择
            return
        self.csvPath = file_path
        try:
            # 2. 读取 CSV 文件
            with open(file_path, mode='r', encoding='utf-8') as file:
                csv_reader = csv.DictReader(file)
                data = list(csv_reader)  # 转换为 List[Dict]

            # 3. 显示结果

            # 显示前5行（避免数据过多卡顿）
            # for i, row in enumerate(data):
                # self.text_edit.append(f"行 {i + 1}: {str(row)}")
            # 返回数据（可在其他地方使用）
            for item in data:
                if 'isRetain' not in item.keys():
                    item['isRetain'] = 1

            self.csvData = data
            ret = readJson(USER_CONFIG_FILE)
            if ret:
                USER_CONFIG = ret
            self.showCsvTable()

            if(len(data)>0):
                row = USER_CONFIG['selectRow']
                srow = 0
                if len(data)>row:
                    srow = row
                self.csvTable.selectRow(srow)
            return data

        except UnicodeDecodeError:
            pass
        except Exception as e:
            pass
    def showCsvTable(self):
        # 1. 设置表格行列数
        data = self.csvData
        self.csvTable.clear()
        self.csvTable.setRowCount(len(data))
        self.csvTable.setColumnCount(len(data[0]))
        # self.csvTable.setSizeAdjustPolicy(QTableWidget.AdjustToContents)
        # self.csvTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # 2. 设置表头（使用字典的键）
        headers = list(data[0].keys())
        self.csvTable.setHorizontalHeaderLabels(headers)

        # 3. 填充数据
        for row_idx, row_data in enumerate(data):
            for col_idx, key in enumerate(headers):

                value = row_data.get(key, "")
                # print(key)
                # print(value)
                item = QTableWidgetItem(str(value))
                item.setTextAlignment(Qt.AlignCenter)  # 文本居中
                self.csvTable.setItem(row_idx, col_idx, item)

        # 4. 自动调整列宽
        self.csvTable.resizeColumnsToContents()

        adjust_columns_width(self.csvTable)


    def showCsvTableRow(self):
        selected_row = self.csvTable.currentRow()
        if selected_row == -1:  # 未选中任何行
            return

        # 获取该行所有单元格数据
        row_data = {}
        for col in range(self.csvTable.columnCount()):
            header = self.csvTable.horizontalHeaderItem(col).text()
            value = self.csvTable.item(selected_row, col).text()
            row_data[header] = value
        if self.csvData[selected_row].get('isRetain','1')=='1':
            self.isRetainCheck.setChecked(True)
        else:
            self.isRetainCheck.setChecked(False)
        grid = QGridLayout()

        # grid.setSpacing(10)  # 设置间距
        if self.csvWidget.layout():
            grid = self.csvWidget.layout()
            wids = []


            for i in reversed(range(grid.count())):
                item = grid.takeAt(i)  # 从布局中移除子项
                if item.widget():
                    # item.widget().deleteLater()
                    wids.append(item)
            for item in wids:
                # grid.removeWidget(item)
                # grid.removeItem(item)
                if item.widget():
                    item.widget().deleteLater()
        else:
            self.csvWidget.setLayout(grid)
        row, col = 0, 0
        rowheight=30
        for key, value in row_data.items():
            # 第一列：属性名 + 冒号
            lbl_key = QLabel(f"{key}:")
            lbl_key.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

            # 第三列：属性值
            showValue = value
            if len(showValue)>20:
                showValue = showValue[:20]+'...'
            lbl_value = QLabel(showValue)
            lbl_value.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)

            # 添加到网格
            grid.addWidget(lbl_key, row, col)
            grid.addWidget(lbl_value, row, col +2)
            rowheight = lbl_value.sizeHint().height()*2
            # 更新行和列
            col += 3
            if col >= 9:  # 每行3组（3列x3=9，因为每组占3列）
                col = 0
                row += 1

        self.csvWidget.setFixedHeight(rowheight*row)
        self.csvWidget.setFixedWidth(1000)
        USER_CONFIG['selectRow'] = selected_row
        saveJson(USER_CONFIG_FILE,USER_CONFIG)
        self.showImg()
    def showGraphic(self,graphicsView,imgpath):
        # baseDir = str(Path(self.csvPath).parent) + '/'
        # imgpaths = self.csvData[self.csvTable.currentRow()]['PATH'].split(';')
        # print('paths', imgpaths)
        pixmap = QPixmap(imgpath)
        # pixmap1= QPixmap('C:\\Users\\dell\\Pictures\\1.bmp')
        scene = QGraphicsScene()
        if not graphicsView.scene():
            graphicsView.setScene(scene)
        graphicsView.scene().addPixmap(pixmap)
        # 显示图片居中
        view_width = graphicsView.viewport().width()
        pixmap_width = pixmap.width()

        if pixmap_width > 0:
            scale_factor = view_width / pixmap_width
            graphicsView.resetTransform()  # 重置之前的变换
            graphicsView.scale(scale_factor, scale_factor)

            # 计算居中位置
            scaled_height = pixmap.height() * scale_factor
            view_height = graphicsView.viewport().height()
            if scaled_height < view_height:
                # 垂直居中
                y_offset = (view_height - scaled_height) / 2 / scale_factor
                graphicsView.setSceneRect(-0, -y_offset,
                                               pixmap.width(), pixmap.height() + y_offset * 2)
            else:
                graphicsView.setSceneRect(0, 0, pixmap.width(), pixmap.height())
    def showImg(self):

        baseDir = str(Path(self.csvPath).parent) + '/'
        imgpaths = self.csvData[self.csvTable.currentRow()]['PATH'].split(';')
        imgpath1 = baseDir+imgpaths[0]
        imgpath2 = baseDir + imgpaths[1]
        imgpath3 = baseDir + imgpaths[2]

        self.showGraphic(self.graphicsView,imgpath1)
        self.showGraphic(self.graphicsView_2, imgpath2)
        self.showGraphic(self.graphicsView_3, imgpath3)
        # print('paths',imgpaths)
        # pixmap = QPixmap(baseDir+imgpaths[2])
        # # pixmap1= QPixmap('C:\\Users\\dell\\Pictures\\1.bmp')
        # scene = QGraphicsScene()
        # if not self.graphicsView.scene():
        #     self.graphicsView.setScene(scene)
        # self.graphicsView.scene().addPixmap(pixmap)
        # #显示图片居中
        # view_width = self.graphicsView.viewport().width()
        # pixmap_width = pixmap.width()
        #
        # if pixmap_width > 0:
        #     scale_factor = view_width / pixmap_width
        #     self.graphicsView.resetTransform()  # 重置之前的变换
        #     self.graphicsView.scale(scale_factor, scale_factor)
        #
        #     # 计算居中位置
        #     scaled_height = pixmap.height() * scale_factor
        #     view_height = self.graphicsView.viewport().height()
        #     if scaled_height < view_height:
        #         # 垂直居中
        #         y_offset = (view_height - scaled_height) / 2 / scale_factor
        #         self.graphicsView.setSceneRect(-0, -y_offset,
        #                           pixmap.width(), pixmap.height() + y_offset * 2)
        #     else:
        #         self.graphicsView.setSceneRect(0, 0, pixmap.width(), pixmap.height())

    def prevOrNext(self,orientation):
        cRow = self.csvTable.currentRow()
        # if cRow==0 or cRow==self.csvTable.rowCount()-1:
        #     return
        if orientation=='up':
            if cRow==0:
                return
            cRow-=1
        else:
            if cRow==self.csvTable.rowCount()-1:
                return
            cRow+=1
        self.csvTable.selectRow(cRow)
    def upFunc(self):
        self.prevOrNext('up')
    def downFunc(self):
        self.prevOrNext('down')
    def isRetain(self):
        index = self.csvTable.currentRow()
        if self.isRetainCheck.isChecked():
            self.csvData[index]['isRetain'] = '1'
        else:#剔除
            self.csvData[index]['isRetain'] = '0'
        # self.showCsvTable()
        new_data=[]
        for key,value in self.csvData[index].items():
            new_data.append(value)
        #刷新表格行数据和详情
        modify_row(self.csvTable,index, new_data)
        self.showCsvTableRow()

    def saveCsv(self):
        path = Path(self.csvPath).parent
        filename = str(path)+'/sample_data'+getTimeStamp()+'.csv'
        if len(self.csvData)>0:
            fieldnames = self.csvData[0].keys()
            with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
                writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
                # 写入表头
                writer.writeheader()
                # 写入数据行
                writer.writerows(self.csvData)

        print(f'数据已保存到 {filename}')
        QMessageBox.information(None, "成功", f"数据已保存到 {filename}")
if __name__ == '__main__':
    app = QApplication(sys.argv)  # 创建APP
    win = MainWindow()  # 创建主窗口
    win.show()  # 显示窗口
    sys.exit(app.exec())  # 程序运行

